<template>
  <div class="layOut">
    <el-card>
      <div class="header">
        <span class="header_text">最近企微客户同步时间：2022/12/24 12:24:24</span>
        <div>
          <el-button
            type="primary"
            :icon="Plus"
            @click="addEnterprise"
          >新增企业属性</el-button>
        </div>
      </div>
    </el-card>
    <div
      class="table-box"
      v-if="tabList.length"
    >
      <el-table
        id="tableRef"
        v-if="showTable"
        :row-class-name="tableRowClassName"
        header-row-class-name="table_header_title"
        class="configure-table-box"
        :data="tabList"
        style="width: 100%"
      >
        <el-table-column width="55">
          <template #default="scope">
            <img
              src="@/assets/customer/sort-icon.png"
              v-if="scope.$index!= 0 && scope.$index != tabList.length-1"
              class="sortImg"
              alt=""
            />
          </template>
        </el-table-column>
        <el-table-column
          label="属性名"
          prop="name"
        />
        <el-table-column
          prop="typeName"
          label="格式"
        >
          <template #default="scope">
            {{ scope.row.typeName || '--' }}
          </template>
        </el-table-column>
        <el-table-column label="选项内容">
          <template #default="scope">
            {{ scope.row.content || '--' }}
          </template>
        </el-table-column>
        <el-table-column label="限制">
          <template #default="{row}"> {{ row.max_length ? row.max_length  : '--' }} </template>
        </el-table-column>
        <el-table-column label="状态">
          <template #default="{row}"> {{ row.is_enable ? row.is_enable == 1 ? '已开启' : "未开启" : "--" }} </template>
        </el-table-column>
        <el-table-column label="类型">
          <template #default="{row}">
            <span>{{row.is_system ? row.is_system == 1 ? "系统" : "自定义" : '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="必填">
          <template #default="{row}">
            <span>{{row.is_required ? row.is_required == 1 ? "是": "否" : "--"}}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建人">
          <template #default="{row}">
            <span>{{row.created_name ? row.created_name : "--"}}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          width="180"
        >
          <template #default="{row}">
            <span>{{row.created_at ? row.created_at : "--"}}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          fixed="right"
          width="220"
        >
          <template #default="scope">
            <div
              class="table-item"
              :data-id="scope.$index"
            >
              <el-button
                size="small"
                class="btn_item"
                @click="start(scope.row)"
              >{{scope.row.is_enable == 1 ? "关闭" : "开启"}}</el-button>
              <el-button
                size="small"
                class="btn_item"
                @click="edit(scope.row)"
                v-if="scope.row.is_system == 2"
              >编辑</el-button>
              <el-button
                size="small"
                class="btn_item"
                v-if="scope.row.is_system == 2"
                @click="del(scope.row)"
              >删除</el-button>
            </div>

          </template>
        </el-table-column>
      </el-table>
      <div class="pageLimit-box"> </div>
    </div>
  </div>
  <Dialog :appDialog="appDialog">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
    >
      <el-form-item
        label="属性名称"
        prop="attr_name"
      >
        <el-input
          maxlength="15"
          show-word-limit
          v-model="ruleForm.attr_name"
          placeholder="请输入属性名称"
        />
      </el-form-item>
      <el-form-item
        label="属性格式"
        prop="attr_type"
      >
        <el-select
          v-model="ruleForm.attr_type"
          placeholder="请选择属性格式"
        >
          <el-option
            v-for="item in typeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="ruleForm.attr_type == 'textbox' || ruleForm.attr_type == 'textarea'"
        label="文本限制"
        prop="max_length"
      >
        <el-input
          v-model.number="ruleForm.max_length"
          placeholder="请输入文本限制"
        ></el-input>
      </el-form-item>
      <el-form-item
        v-if="ruleForm.attr_type == 'select' || ruleForm.attr_type == 'muti_select'"
        label="选项内容"
        prop="content"
      >
        <el-input
          v-model="ruleForm.content"
          type="textarea"
          placeholder="每个选项为一行，最多30个选项"
          @blur="checkTextarea"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="是否开启"
        prop="is_enable"
      >
        <el-radio-group v-model="ruleForm.is_enable">
          <el-radio :label="2">开启</el-radio>
          <el-radio :label="1">关闭</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="是否必填"
        prop="is_required"
      >
        <el-select
          v-model="ruleForm.is_required"
          placeholder="请选择是否必填"
        >
          <el-option
            label="是"
            :value="1"
          />
          <el-option
            label="否"
            :value="2"
          />
        </el-select>
      </el-form-item>
    </el-form>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick } from 'vue'
import Sortable from 'sortablejs'
import { Plus } from '@element-plus/icons-vue'
import { getEnterprise, sortEnterprise, addNewEnterprise, editEnterprise, delEnterprise, startOrDel } from '../api'
import Dialog from '@/components/Dialog.vue'
import { deepCopy } from '@/utils/helper'
import { ElMessage, ElMessageBox } from 'element-plus'

const tabList = ref([])
const showTable = ref(false)
const ruleFormRef = ref()
const editId = ref()
const typeList = reactive([
  { label: '单行文本', value: 'textbox' },
  { label: '多行文本', value: 'textarea' },
  { label: '单选', value: 'select' },
  { label: '多选', value: 'muti_select' },
  { label: '日期', value: 'date' },
  { label: '手机号', value: 'mobile' },
  { label: '邮箱', value: 'email' },
  { label: '区域', value: 'pca' },
  { label: '图片', value: 'picture' }
])
const ruleForm = reactive({
  attr_name: '',
  attr_type: '',
  attr_val: [],
  max_length: '',
  is_enable: '',
  is_required: '',
  content: ''
})
const rules = reactive({
  attr_name: [{ required: true, message: '请输入属性名称', trigger: 'blur' }],
  attr_type: [{ required: true, message: '请选择属性格式', trigger: 'blur' }],
  content: [{ required: true, message: '请填写选项内容', trigger: 'blur' }],
  is_enable: [{ required: true, message: '请选择是否开启', trigger: 'blur' }],
  max_length: [{ required: true, message: '请输入文本限制', trigger: 'blur' }],
  is_required: [{ required: true, message: '请选择是否必填', trigger: 'blur' }]
})
const setSortableFun = () => {
  let nowIndex
  let copyTableList
  nextTick(() => {
    let SortableBox = new Sortable(document.querySelector('#tableRef').querySelector('.el-table__body-wrapper tbody'), {
      animation: 100,
      sort: true,
      delay: 0,
      delayOnTouchOnly: false,
      handle: '.can-sort',
      filter: '.no-sort',
      onChoose: function (evt: any) {
        nowIndex = evt.oldIndex
        console.log(evt.oldIndex)
      },
      onMove: function (evt: any, originalEvent: any) {
        console.log(evt)
      },
      //
      onEnd: (evt: any) => {
        copyTableList = JSON.parse(JSON.stringify(tabList.value))
        const data = copyTableList.splice(evt.oldIndex, 1)[0]
        copyTableList.splice(evt.newIndex, 0, data)
        let next_id = ''
        let pre_id = ''
        if (copyTableList[evt.newIndex - 1]) {
          pre_id = copyTableList[evt.newIndex - 1].source_id
        }
        if (copyTableList[evt.newIndex + 1]) {
          next_id = copyTableList[evt.newIndex + 1].source_id
        }
        let arr: any = []
        copyTableList.forEach((item: any, index: number) => {
          arr.push(item.id)
        })
        sortEnterprise({ attr_ids: arr }).then((r: any) => {
          init()
        })
      }
    })
  })
}
const init = () => {
  getEnterprise().then((res: any) => {
    tabList.value = res.map((item: any) => {
      if (item.type) {
        let index = typeList.findIndex((it) => it.value == item.type)
        item.typeName = ''
        if (index > -1) {
          item.typeName = typeList[index].label
        }
      }
      item.attr_val_name = item.attr_val_name ? item.attr_val_name : ''
      return JSON.parse(JSON.stringify(item))
    })
    showTable.value = false
    setTimeout(() => {
      showTable.value = true
      nextTick(() => {
        setSortableFun()
      })
    })
  })
}
init()
const tableRowClassName = (row: any) => {
  if (row.rowIndex == 0 || row.rowIndex == tabList.value.length - 1) {
    return 'no-sort'
  }
  return 'can-sort'
}
const addEnterprise = () => {
  appDialog.visible = true
}
const edit = (data: any) => {
  const { name, type, content, is_enable, is_required, id, max_length,attr_val_name } = data
  ruleForm.attr_name = name
  ruleForm.attr_type = type
  ruleForm.content = content
  ruleForm.is_enable = is_enable
  ruleForm.is_required = is_required
  ruleForm.max_length = max_length
  ruleForm.content =  attr_val_name ? attr_val_name.toString().replace(/,/g, '\n') : ''
  ruleForm.attr_id = id
  appDialog.visible = true
  console.log(data, "数据编辑")
}
const del = (row: any) => {
  ElMessageBox.confirm(`您正在删除企业的【${row.name}】的属性，确定之后，企业的该属性将会被删除，请慎重！`, '温馨提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    delEnterprise({ attr_id: row.id }).then((r: object) => {
      ElMessage.success('删除成功')
      init()
    })
  })
}
const start = (row: any) => {
  const params = {
    attr_id: row.id,
    is_enable: row.is_enable == 1 ? 2 : 1
  }
  startOrDel(params).then((res: any) => {
    ElMessage.success('操作成功')
    init()
  })
}
// 检查是否输入标准  防止ssr
const checkTextarea = () => {
  let str = ruleForm.content
  str = str.replace(/<script>/g, '')
  str = str.replace(/alert/g, '')
  ruleForm.content = str
}
const getContentArr = (str: string) => {
  if (!str.trim().length) {
    return []
  }
  let arr: any = []
  str.split('\n').forEach((item) => {
    if (item.length > 0) {
      arr.push(item)
    }
  })
  arr = Array.from(new Set(arr)) //去除重复的
  return arr
}
const cancelHandel = (refresh?: number) => {
  if (!ruleFormRef.value) return
  Object.keys(ruleForm).reduce((val, key) => {
    if (ruleForm[key] == 'attr_val') {
      ruleForm[key] = []
    } else {
      ruleForm[key] = ''
    }
  }, {})
  appDialog.visible = false
  if (refresh == 1) init()
}
const submitHandel = async () => {
  if (!ruleFormRef.value) return
  await ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      ruleForm.attr_val = getContentArr(ruleForm.content)
      const params = deepCopy(ruleForm)
      delete params.content
      if (params.attr_id) {
        editEnterprise(params).then((res: any) => {
          ElMessage.success('编辑成功')
          cancelHandel(1)
        })
      } else {
        addNewEnterprise(params).then((res: any) => {
          ElMessage.success('新建成功')
          cancelHandel(1)
        })
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}
// 弹框配置项
const appDialog = reactive({
  visible: false,
  title: '新增企业属性',
  width: '30%',
  cancel: cancelHandel,
  submit: submitHandel,
  cancelText: '取消',
  submitText: '提交',
  isInit: false, //是否重置
  isChooseDisabled: false //重新打开传递进来的数据是否重置
})
</script>

<style lang="scss" scoped>
.layOut {
  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    &_text {
      font-size: 14px;
    }
  }
  .table-box {
    margin-top: 17px;
    // overflow: hidden;
    .sortImg {
      width: 13px;
      height: 11px;
    }
    .table-item {
      display: flex;
      justify-content: flex-start;
      div {
        // width: 80px;
        height: 24px;
        background: #ffffff;
        border-radius: 2px;
        border: 1px solid #eaeaea;
        line-height: 24px;
        margin-right: 10px;
        font-size: 14px;
        font-family: STHeitiSC-Light, STHeitiSC;
        font-weight: 300;
        color: #33302d;
        text-align: center;
        cursor: pointer;
      }
      :deep .btn_item {
        padding: 0px 16px;
        min-height: 24px;
      }
    }
  }
  .pageLimit-box {
    padding-top: 20px;
  }
}
.el-select {
  width: 100%;
}
</style>